package com.zwb.service.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.hutool.extra.mail.Mail;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zwb.service.common.CacheConstant;
import com.zwb.service.common.MailConstants;
import com.zwb.service.common.utils.ConversionUtil;
import com.zwb.service.pojo.*;
import com.zwb.service.service.*;
import com.zwb.service.vo.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author 头发又黑又长
 * @Date 2022/9/7 16:23
 * @email zwb15083976291@163.com
 */
@Api(tags = "员工管理")
@RestController
@RequestMapping("/employee/basic")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IPoliticsStatusService politicsStatusService;

    @Autowired
    private IPositionService positionService;

    @Autowired
    private INationService nationService;

    @Autowired
    private IDepartmentService departmentService;

    @Autowired
    private IJoblevelService joblevelService;

    @Autowired
    private IMailLogService mailLogService;

    @Autowired(required = false)
    private RabbitTemplate rabbitTemplate;


    @ApiOperation("获取所有员工信息")
    @GetMapping("/")
    public R getEmployees(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            Date beginDateScope, Date endDateScope,
            Employee employee
    ) {

        Page<Employee> page = employeeService.getEmployeeByPage(current, size, beginDateScope, endDateScope, employee);
        return R.success(page);
    }

    @ApiOperation("获取所有政治面貌")
    @Cacheable(value = CacheConstant.CACHEABLE_VALUE_3_DAT, key = "'politicsstatus'")
    @GetMapping("/politicsstatus")
    public R<List<PoliticsStatus>> getPoliticsstatus() {
        return R.success(politicsStatusService.list());
    }


    @ApiOperation("获取所有职位")
    @GetMapping("/positions")
    @Cacheable(value = CacheConstant.CACHEABLE_VALUE_3_DAT, key = "'position'")
    public R<List<Position>> getPosition() {
        return R.success(positionService.list());
    }


    @ApiOperation("获取新员工工号")
    @GetMapping("/maxWorkID")
    public R maxWorkID() {
        String id = String.format("%08d", employeeService.maxWorkID());
        return R.success(new ModelMap("id", id));
    }

    @ApiOperation("添加员工")
    @PostMapping("/")
    public R addEmployee(@RequestBody Employee employee) {
        if (employeeService.addEmployee(employee)) {
            this.sendMailByEmployee(employeeService.getEmployeesByIn(Collections.singletonList(employee.getId())).get(0));
            return R.success("添加员工信息成功");
        }
        return R.error("添加员工信息失败");
    }


    private void sendMailByEmployee(Employee employee) {

        /* id */
        String msgID = UUID.randomUUID().toString();
        // 数据库记录发送的消息
        MailLog mailLog = new MailLog();
        mailLog.setMsgId(msgID);
        mailLog.setEid(employee.getId());
        mailLog.setStatus(0);
        mailLog.setRouteKey(MailConstants.EMAIL_ROUTING_KEY);
        mailLog.setExchange(MailConstants.EXCHANGE_EMAIL);
        mailLog.setCount(0);
        /* 执行时间，当前时间添加一分钟 */
        /*
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.MINUTE, 1);
        mailLog.setTryTime(instance.getTime());
        */
        mailLog.setTryTime(ConversionUtil.localDateTimeToDate(LocalDateTime.now().plusMinutes(MailConstants.MSG_TIMEOUT)));
        mailLog.setStatus(MailConstants.DELIVERING);
        mailLog.setCreateTime(new Date());
        mailLog.setUpdateTime(new Date());
        mailLogService.save(mailLog);


        // 发送邮箱
        rabbitTemplate.convertAndSend(MailConstants.EXCHANGE_EMAIL,
                MailConstants.EMAIL_ROUTING_KEY, employee, new CorrelationData(msgID));
    }


    @ApiOperation("更新员工信息")
    @PutMapping("/")
    public R updateEmployee(@RequestBody Employee employee) {
        return employeeService.updateById(employee) ? R.success("更新员工信息成功")
                : R.error("更新员工信息失败");

    }

    @ApiOperation("删除员工信息")
    @DeleteMapping("/{id}")
    public R deleteEmployee(@PathVariable("id") Integer id) {
        return employeeService.removeById(id) ? R.success("删除员工信息成功")
                : R.error("删除员工信息失败");

    }


    @ApiOperation("导出员工数")
    @GetMapping(value = "export", produces = {"application/octet-stream"}) // 设置流方式传输
    public void exportEmployee(@RequestParam(required = false) List<Integer> ids, HttpServletResponse response) throws IOException {
        List<Employee> employees = employeeService.getEmployeesByIn(ids);
        /* 创建excel 信息 */
        ExportParams params = new ExportParams("员工表", "员工表", ExcelType.HSSF);
        /* 创建工作铺 */
        Workbook sheets = ExcelExportUtil.exportExcel(params, Employee.class, employees);

        try (ServletOutputStream outputStream = response.getOutputStream();) {
            /* 流形式传输 */
            response.setContentType("application/octet-stream");
            /* 防止中文乱码 */
            response.setHeader("content-disposition",
                    "attachment;filename=" + URLEncoder.encode("员工表.xls", "UTF-8"));
            sheets.write(outputStream);
        }
    }

    @ApiOperation("导入员工数据")
    @PostMapping("/import")
    public R importEmployee(@RequestPart("file") MultipartFile multipartFile) throws IOException {
        ImportParams importParams = new ImportParams();
        importParams.setTitleRows(1); // 去掉标题行
        List<Employee> employees;
        try {
            employees = ExcelImportUtil.importExcel(multipartFile.getInputStream(), Employee.class, importParams);
        } catch (Exception e) {
            return R.error("解析错误文件错误：" + e.getMessage());
        }
        List<Nation> nations = nationService.list(); // 获取所有民族
        List<PoliticsStatus> politicsStatuses = politicsStatusService.list(); // 所有政治面貌
        List<Department> departments = departmentService.list(); // 所有部门
        List<Position> positions = positionService.list(); // 所有职位
        List<Joblevel> joblevels = joblevelService.list(); // 获取所有职称
        for (Employee employee : employees) {
            // 设置民族ID
            employee.setNationId(nations.get(nations.indexOf(employee.getNation())).getId());
            // 设置职位ID
            employee.setPosId(positions.get(positions.indexOf(employee.getPosition())).getId());
            // 设置政治面貌
            employee.setPoliticId(politicsStatuses.get(politicsStatuses.indexOf(employee.getPoliticsStatus())).getId());
            // 设置部门id
            employee.setPosId(positions.get(positions.indexOf(employee.getPosition())).getId());
            // 设置职称
            employee.setJobLevelId(joblevels.get(joblevels.indexOf(employee.getJoblevel())).getId());
        }
        return employeeService.saveBatch(employees) ? R.success("导入文件成功") : R.error("导入失败");
    }

}
